#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

class Solution
{
public:
    int minCostII(vector<vector<int>> &costs)
    {
        if (costs.size() == 0)
            return 0;
        int n = costs[0].size();
        int Min = 0;
        int secondMin = 0;
        int color = -1;
        for (vector<int> cost : costs)
        {
            int preColor = color;
            int preMin = Min;
            int preSecondMin = secondMin;
            Min = INT32_MAX;
            secondMin = INT32_MAX;
            for (int i = 0; i < n; i++)
            {
                int price = i == preColor ? preSecondMin + cost[i] : preMin + cost[i];
                //计算与上一个是否重复
                if (price < secondMin)
                {
                    if (price < Min)
                    {
                        secondMin = Min;
                        Min = price;
                        color = i;
                    }
                    else
                    {
                        secondMin = price;
                    }
                }
            }
        }
        return Min;
    }
};
